#! /bin/bash
#
#   mksite - Upload CZMQ manual to czmq.zeromq.org/manual:
#
#   Author: Pieter Hintjens <ph@imatix.com>
#   License: public domain
#
#   syntax: mksite
#

#   Export so child scripts can access these
export UPLOAD=1             #   If 0, don't actually upload
export WEBSITE=czmq         #   Use ZeroMQ API site
export TOOLDIR=`dirname $0`
export OWN_DIR=$PWD

# This function uploads a file to wikidot
# Error in upload will cause the script to exit with non-zero status

function do_upload {
    wdput $WEBSITE $1 $2 "$3"
    if [ $? != 0 ]; then
        echo "Error uploading file to wikidot"
        exit 1
    fi
}

#   This function builds and uploads one branch's documentation

function do_branch {
    export CZMQ_DIR=$1
    export BRANCH=$2
    export CATEGORY=$3

    echo "Building docs for $CZMQ_DIR $BRANCH..."
    cd $CZMQ_DIR
    git pull origin master
    git checkout -q $BRANCH
    echo "Running ./autogen.sh && ./configure..."
    sh ./autogen.sh > /dev/null 2>&1
    ./configure --quiet
    cd doc
    make -j4 --quiet
    rm -f *.xml    #   Makefile does not detect version differences for XML
    for a in z*.txt; do
        make `basename $a .txt`.xml
    done

    echo "Generating XML pages for manual..."
    FILES=
    DEPRECATED=
    #   First all current classes, then deprecated ones
    for FILE in czmq z*.txt; do
        BASE=`basename $FILE .txt`
        make --quiet $BASE.xml;
        head $FILE | egrep -q deprecated
        if [ $? -eq 0 ]; then
            DEPRECATED="$DEPRECATED $BASE"
        else
            FILES="$FILES $BASE"
        fi
    done
    FILES="$FILES $DEPRECATED"

    cd $OWN_DIR
    echo "Generating Wikidot pages..."
    for FILE in $FILES; do
        perl $TOOLDIR/xml2wd.pl $CZMQ_DIR/doc/$FILE.xml > $FILE.wd
    done

    if [ $UPLOAD -eq 1 ]; then
        #   Send table of contents as category:_start
        do_upload $CATEGORY "_start" "CZMQ API"

        #   Send template as category:_template
        cp _template.txt _template.wd
        do_upload $CATEGORY "_template" "Category template - generated"

        #   Now send individual man pages
        for FILE in $FILES; do
            TITLE=`egrep --after-context 1 PAGE_TITLE $FILE.wd | egrep $FILE`
            do_upload $CATEGORY $FILE $TITLE
        done
    fi

    rm *.wd
    #   Restore repository to master branch
    cd $CZMQ_DIR
    git checkout -q master
    cd $OWN_DIR
}

if [ ! -z "$3" ]; then
    if [ ! -f $1/doc/czmq.txt ]; then
        echo "Can't find CZMQ doc directory in $1"
        exit
    fi
    do_branch $1 $2 $3
else
    echo "Syntax: apione <czmq_dir> <branch> <category>"
fi
